package com.yonyou.iuap.jxzy.service;

import static com.yonyou.iuap.baseservice.intg.support.ServiceFeature.BPM;
import static com.yonyou.iuap.baseservice.intg.support.ServiceFeature.LOGICAL_DEL;
import static com.yonyou.iuap.baseservice.intg.support.ServiceFeature.REFERENCE;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.transaction.Transactional;

import oracle.net.aso.f;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.baseservice.intg.service.GenericIntegrateService;
import com.yonyou.iuap.baseservice.intg.support.ServiceFeature;
import com.yonyou.iuap.baseservice.ref.service.RefCommonService;
import com.yonyou.iuap.jxzy.dao.AcceptancePaperMapper;
import com.yonyou.iuap.jxzy.dao.PoundderLiverMapper;
import com.yonyou.iuap.jxzy.entity.AcceptancePaper;
import com.yonyou.iuap.mvc.type.SearchParams;
import com.yonyou.uap.ieop.security.exception.BusinessException;

@Service
/**
 * AcceptancePaper CRUD 核心服务,提供逻辑删除/乐观锁
 */
public class AcceptancePaperService extends
		GenericIntegrateService<AcceptancePaper> {

	private Logger logger = LoggerFactory
			.getLogger(AcceptancePaperService.class);

	@Autowired
	private AcceptancePaperMapper acceptancePaperMapper;

	@Autowired
	private PoundderLiverMapper poundderLiverMapper;

	/**
	 * 图片上传
	 */
	@Autowired
	private IandDFileService fileService;

	@Autowired
	public void setAcceptancePaperMapper(
			AcceptancePaperMapper acceptancePaperMapper) {
		this.acceptancePaperMapper = acceptancePaperMapper;
		super.setGenericMapper(acceptancePaperMapper);
	}

	@Autowired
	private RefCommonService refService;

	public List selectListByExcelData(List idsList) {
		List list = acceptancePaperMapper.selectListByExcelData(idsList);
		list = refService.fillListWithRef(list);
		return list;
	}

	public List<AcceptancePaper> findByTime(String startTime, String endTime, String usrcode,String serialNo) {
		List<AcceptancePaper> list = acceptancePaperMapper.findByTime(
				startTime, endTime, usrcode,serialNo);
		/*Set set = new HashSet();
		set.addAll(list);*/
		return list;
	}

	/**
	 * @CAU 可插拔设计
	 * @return 向父类 GenericIntegrateService 提供可插拔的特性声明
	 */
	@Override
	protected ServiceFeature[] getFeats() {
		return new ServiceFeature[] { REFERENCE, BPM, LOGICAL_DEL };
	}

	public Integer saveParam(AcceptancePaper acceptancePaper) {
		// TODO Auto-generated method stub
		Integer saveNum = acceptancePaperMapper.saveParam(acceptancePaper);
		return saveNum;

	}

	/**
	 * 根据id获取数据
	 * 
	 * @param map
	 * @return
	 */
	public List<AcceptancePaper> getChildListById(Map<String, Object> map) {
		List<AcceptancePaper> list = acceptancePaperMapper
				.getChildListById(map);
		//
		return list;
	}

	public Page<AcceptancePaper> getChildListById(PageRequest pageRequest,
			SearchParams searchParams) {
		return acceptancePaperMapper.getChildListById2(searchParams,
				pageRequest).getPage();
	}

	public List<String> getQualityGrade(String pk_org) {
		// TODO Auto-generated method stub
		List<String> list = acceptancePaperMapper.getQualityGrade(pk_org);
		return list;
	}

	public Map<String, Object> getUnit(String materialVariety,
			String qualityGrade) {

		return acceptancePaperMapper.getUnit(materialVariety, qualityGrade);
	}

	public void booleanCheck(String id, String modifierReason, String serialNo,
			String userName) throws BusinessException {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			String poundBillSataus = poundderLiverMapper
					.getPoundStatus(serialNo);// 根据序列号获取磅单状态（完成和未完成）
			/**
			 * 磅单状态： 目前就是判断 1 和 2 TODO 1未完成状态 2完成状态 3修改待审 4作废待审 5作废 6待回皮
			 */
			logger.error("磅单状态:" + poundBillSataus);

			if ("未完成状态".equals(poundBillSataus)) {
				logger.error("重检信息:" + modifierReason + "用户名" + userName
						+ "序列号" + serialNo + "id:" + id);
				Integer num = acceptancePaperMapper.booleanCheck(id,
						modifierReason, userName);// 增加修改原有，dr=1
				// Integer
				// num=acceptancePaperMapper.booleanCheck(id,modifierReason);//增加修改原有，dr=1
				logger.error("修改条数:" + num);
				if (num == 0) {
					throw new BusinessException("重检失败");
				}
			}
		} catch (Exception e) {
			throw new BusinessException("重检失败,该磅单已完成");
		}

	}

	/**
	 * 查询 iupa
	 * 
	 * @param pageRequest
	 * @param searchParams
	 * @return
	 */
	public Page<AcceptancePaper> selectAllByList(PageRequest pageRequest,
			SearchParams searchParams) {

		List<AcceptancePaper> list = new ArrayList<AcceptancePaper>();
		Page<AcceptancePaper> page2 = acceptancePaperMapper.selectAllByPage(
				pageRequest, searchParams).getPage();
		/*
		 * list=page2.getContent(); Set set=new HashSet(); set.addAll(list);
		 * List<AcceptancePaper> listparaPapers=new
		 * ArrayList<AcceptancePaper>(set);
		 * System.out.println(listparaPapers.toString()); List<String>
		 * serialNo=new ArrayList<String>(); for (AcceptancePaper
		 * acceptancePaper :listparaPapers) {
		 * serialNo.add(acceptancePaper.getSerialNo()); } Page<AcceptancePaper>
		 * page=null; List<AcceptancePaper> list2=new
		 * ArrayList<AcceptancePaper>(); if (serialNo.size()>0) {
		 * page=acceptancePaperMapper
		 * .selectAllByListByIds(searchParams,pageRequest,serialNo).getPage();
		 * 
		 * }
		 */
		return page2;

	}

	/**
	 * TODO 图片加载没有保持事物的统一性 图片上传和插入国内数据要保持一致
	 * 
	 * @param acPaper
	 * @throws BusinessException
	 * @throws IOException
	 * @throws InterruptedException
	 */

	@Transactional
	// @Synchronized
	public void insertAndCheckout(AcceptancePaper acPaper)
			throws BusinessException, IOException, InterruptedException {

		//		synchronized (acPaper) {
		List<AcceptancePaper> firstDataParam = acceptancePaperMapper
				.getByFirst(acPaper.getSerialNo());
		// 根据序列号获取磅单表的pk_poundbill
		String pk_poundbill = poundderLiverMapper.getPK_Poundbill(acPaper
				.getSerialNo());

		// 校验
		List<String> heapNoList = new ArrayList<String>();// 堆号
		List<String> nameList = new ArrayList<String>();// 姓名
		List<String> forkliftNoList = new ArrayList<String>();// 叉车工工号
		List<String> returnGoodsReasonList = new ArrayList<String>();// 退货
		if (firstDataParam.size() > 0 && firstDataParam != null) {
			for (AcceptancePaper acceptancePaper : firstDataParam) {
				// 堆号
				if (null != acceptancePaper.getHeapNo()) {
					heapNoList.add(acceptancePaper.getHeapNo());
				}
				nameList.add(acceptancePaper.getInspector());
				// 叉车工工号
				if (null != acceptancePaper.getForkliftNo()) {
					forkliftNoList.add(acceptancePaper.getForkliftNo());
				}
				// 退货
				if (null != acceptancePaper.getReturnGoods()) {
					returnGoodsReasonList.add(acceptancePaper.getReturnGoods());
				}
			}
		}

		String firstData = null;// 是否第一人称

		Integer num = 0;
		synchronized (acPaper) {
			// 第一次提交保存
			if (firstDataParam.size() == 0) {
				firstData = "Y";
				acPaper.setFirstData(firstData);
				num = acceptancePaperMapper.saveParam(acPaper);
				return;

			} else {
				for (int i = 0; i < firstDataParam.size(); i++) {
					AcceptancePaper acceptancePaper2 = new AcceptancePaper();
					acceptancePaper2 = firstDataParam.get(i);
					Integer dr = acceptancePaper2.getDR();
					String isFirstData = acceptancePaper2.getFirstData();

					if (nameList.contains(acPaper.getInspector())) {
						throw new BusinessException("您已提交,不能再次提交");
					}
					// 校验
					this.secondVerIfy(heapNoList, forkliftNoList,
							returnGoodsReasonList, acceptancePaper2, acPaper);
					firstData = "N";
					acPaper.setFirstData(firstData);
					num = acceptancePaperMapper.saveParam(acPaper);
					// 更新磅单 TODO 补丁不能注释掉
					this.insertPoundBIll_b(pk_poundbill, acPaper, firstData);
					if (num == 0) {
						throw new BusinessException("插入检验数据失败!");

					}
					break;
				}
			}
		}
		//		}
	}
	
	//更新检验时价格数据
	public void mergeSerialUnit(AcceptancePaper acPaper){
		acceptancePaperMapper.mergeSerialUnit(acPaper);
	}

	public void merge2(AcceptancePaper acPaper){
		acceptancePaperMapper.mergeSerialUnit(acPaper);
	}

	/**
	 * APP国内废纸校验 
	 * @param heapNoList
	 * @param forkliftNoList
	 * @param returnGoodsReasonList
	 * @param acceptancePaper2
	 * @param acPaper
	 * @throws BusinessException
	 */
	private void secondVerIfy(List<String> heapNoList,
			List<String> forkliftNoList, List<String> returnGoodsReasonList,
			AcceptancePaper acceptancePaper2, AcceptancePaper acPaper)
			throws BusinessException {
		/**
		 * 校验 堆号，物料品种，质量等级，开包件数 TODO 第一次校验业务需求变更，堆号不用校验 第二次：堆号 叉车工工号，退货
		 */
		if (heapNoList != null && heapNoList.size() > 0
				&& heapNoList.get(0) != null) {
			String heapNo = heapNoList.get(0);
			if (!"".equals(acPaper.getHeapNo())
					&& !heapNo.equals(acPaper.getHeapNo())
					&& !"".equals(acceptancePaper2.getHeapNo())) {
				throw new BusinessException("堆号不一致");
			}
		}
		if (forkliftNoList != null && forkliftNoList.size() > 0
				&& forkliftNoList.get(0) != null) {
			String forkliftNo = forkliftNoList.get(0);
			if (!"".equals(acPaper.getForkliftNo())
					&& !forkliftNo.equals(acPaper.getForkliftNo())) {
				throw new BusinessException("叉车工工号不一致");
			}
		}

		if (returnGoodsReasonList != null && returnGoodsReasonList.size() > 0
				&& returnGoodsReasonList.get(0) != null) {
			String returnGoods = returnGoodsReasonList.get(0);
			if (!"".equals(acPaper.getReturnGoods())
					&& !returnGoods.equals(acPaper.getReturnGoods())) {
				throw new BusinessException("退货不一致");
			}
		}
		if (!"".equals(acPaper.getCheckPoint())
				&& !acceptancePaper2.getCheckPoint().equals(
						acPaper.getCheckPoint())) {
			throw new BusinessException("检验点不一致");
		}
		if (!"".equals(acceptancePaper2.getUnpackNo())
				&& !acceptancePaper2.getUnpackNo()
						.equals(acPaper.getUnpackNo())
				&& !"".equals(acPaper.getUnpackNo())) {
			throw new BusinessException("开包件数不一致");
		}
		if (!"".equals(acceptancePaper2.getMaterialVariety())
				&& !acceptancePaper2.getMaterialVariety().equals(
						acPaper.getMaterialVariety())
				&& !"".equals(acPaper.getMaterialVariety())) {
			throw new BusinessException("物料品种不一致");
		}
		if (!"".equals(acceptancePaper2.getQualityGrade()) && !"".equals(acPaper.getQualityGrade())
				&& !acceptancePaper2.getQualityGrade().equals(
						acPaper.getQualityGrade())) {
			throw new BusinessException("质量等级不一致");
		}

	}

	private void insertPoundBIll_b(String pk_poundbill,
			AcceptancePaper acPaper, String firstData) throws BusinessException {
		// TODO Auto-generated method stub
		if (pk_poundbill == null) {
			throw new BusinessException("没有该磅单");
		}
		/**
		 * 更新数据到磅单子表 抽样区 已经有了 质量等级，平均含水份比，平均含杂质比，扣水分重，杂质重，堆号，开包件数， 含水份比--测水仪
		 */
		// BigDecimal unit = acPaper.getUnit();// 单价
		// String qualityGrade = acPaper.getQualityGrade();// 质量等级
		// String unPackNo = acPaper.getUnpackNo();// 开包件数
		String heapNo = null;// 堆号
		if (acPaper.getHeapNo() == null) {
			heapNo = null;
		} else {
			heapNo = acPaper.getHeapNo();
		}

		// 平均含水分比 平均含杂质比
		AcceptancePaper avgParam = acceptancePaperMapper
				.getParamForSerialNo(acPaper.getSerialNo());
		String averageWaterRatio = String.valueOf(avgParam
				.getAverageWaterRatio());// 平均含水分比
		String averageImpurityRatio = String.valueOf(avgParam
				.getAverageImpurityRatio());// 平均含杂质比
		String averageImpurityWeight = String.valueOf(avgParam
				.getAverageImpurityWeight());// 平均扣杂质重
		String averageDewateringWeight = String.valueOf(avgParam
				.getAverageDewateringWeight());// 平均扣水分重
		/**
		 * TODO 第一次提交可能没有提交堆号 提交的堆号为空，后面提交的人提交堆号则更新上去,二次提交的更新堆号 流程变更
		 * 第一次提交由计量系统做，iuap平台做第二次的修改更新操作(二次提交)
		 */
		/*
		 * if ("Y".equals(firstData)) { Integer num =
		 * poundderLiverMapper.insertPoundBill_b(unit, qualityGrade, heapNo,
		 * unPackNo, averageDewateringWeight, averageImpurityWeight,
		 * averageWaterRatio, averageImpurityRatio, pk_poundbill); if (num == 0)
		 * { throw new BusinessException("插入磅单子表数据失败!"); } }
		 */
		// 二次提交的更新堆号，平均含水分比，平均含杂质比
		Integer updateNum = poundderLiverMapper.updateCheapNo(heapNo,
				averageWaterRatio, averageImpurityRatio,
				averageDewateringWeight, averageImpurityWeight, pk_poundbill);
		if (updateNum == 0) {
			throw new BusinessException("更新磅单子表数据失败!");
		}
	}

	public void iii(AcceptancePaper acPaper) {
		acceptancePaperMapper.mergeSerialUnit(acPaper);
	}
	
}
